package com.marvels.approve.mqueues.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.marvels.approve.common.dto.InsurancePolicyDTO;
import com.marvels.approve.common.dto.LoanApplyContactInfoDTO;
import com.marvels.approve.loan.dao.McamLoanInsurancePolicyInfoMapper;
import com.marvels.approve.loan.dto.McamAcLoanApplyBdInfo;
import com.marvels.approve.loan.dto.McamAcLoanApplyImageInfo;
import com.marvels.approve.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.approve.loan.service.IMcamLoanApplyInfoService;
import com.marvels.approve.mqueues.service.ApproveILoanApplyDataSynchronizeService;
import com.marvels.approve.mqueues.service.ApproveLoanApplySynchronizeApi;
import com.marvels.approve.process.dao.AttachmentInfoDao;
import com.marvels.approve.process.dao.TaskProcessDao;
import com.marvels.approve.process.dto.LaAttachmentDTO;
import com.marvels.approve.process.service.TaskProcessService;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.dto.BasicDataDTO;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.MarvelsLogUtil;

@Service
public class ApproveLoanApplyDataSynchronizeServiceImpl implements ApproveILoanApplyDataSynchronizeService {
	@Autowired
	private ApproveLoanApplySynchronizeApi loanApplySynchronizeApi;
	@Autowired
	private IMcamLoanApplyInfoService mcamLoanApplyInfoService;
	@Autowired
	private AttachmentInfoDao attachmentInfoMapper;
	@Autowired
	private McamLoanInsurancePolicyInfoMapper mcamLoanInsurancePolicyInfoMapper;
	@Autowired
	private TaskProcessDao taskProcessMapper;
	@Autowired
	private TaskProcessService taskProcessService;


	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	@Override
	public McamLoanApplyInfoDTO synchronizeLoanApplyInfo(String loanId) throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info("Synchronize_Data_LoanApplyInfo_loanId:" + loanId);
		McamLoanApplyInfoDTO dto = loanApplySynchronizeApi.queryLoanBasicInfo(loanId);
		MarvelsLogUtil.getInstance().info(loanId + "Synchronize_Data_LoanApplyInfo_dto:" + dto);
		// if(false){
		// throw new MarvelsBusinessException("贷款信息同步失败loanId:"+loanId);
		// }
		if (dto == null) {
			throw new MarvelsBusinessException(loanId + "进件数据为空，所以无法做入库处理！");
		}
		if(StringUtils.isEmpty(dto.getCreatedBy())) {
			dto.setCreatedBy("system");
		}
		if(StringUtils.isEmpty(dto.getUpdatedBy())) {
			dto.setUpdatedBy("system");
		}
		if(dto.getCreatedDate() == null) {
			dto.setCreatedDate(new Date());
		}
		if(dto.getUpdatedDate() == null) {
			dto.setUpdatedDate(new Date());
		}
		if(dto.getPrincipalAmtAct() == null || dto.getPrincipalAmtAct().compareTo(BigDecimal.ZERO) <= 0) {
			dto.setPrincipalAmtAct(dto.getDecisionMoney()==null?dto.getApplyAmount():dto.getDecisionMoney());
		}
//		dto.setCustomerType(dto.getCreditRating());
		// 保存进件表
		String companyTel = dto.getCompanyTel();
		dto.setCompanyTel(null);
		if(StringUtils.isNotEmpty(companyTel)){
			String[] ary = companyTel.split("-");
			for(int i=0;i<ary.length;i++){
				if(i == 0){
					dto.setCompanyCode(ary[i]);
				}else if(i == 1){
					dto.setCompanyTel(ary[i]);
				}else if(i == 2){
					dto.setCompanyExtension(ary[i]);
				}
			}
		}
		mcamLoanApplyInfoService.saveMcamLoanApplyInfo(dto);
		return dto;
	}

	/**
	 * 同步保单数据
	 */
	@SuppressWarnings("unchecked")
	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	@Override
	public List<McamAcLoanApplyBdInfo> synchronizeInsurancePolicy(String loanId) throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info("Synchronize_Data_InsurancePolicy_loanId:" + loanId);
		List<McamAcLoanApplyBdInfo> dto = loanApplySynchronizeApi.queryApplyInfo(loanId);
		MarvelsLogUtil.getInstance().info(loanId+"synchronizeInsurancePolicy_dto:"+dto);
		if (dto == null) {
			return null;
		}
//		InsurancePolicyDTO policyDto = new InsurancePolicyDTO();
		List<InsurancePolicyDTO> dbInfo = this.mcamLoanInsurancePolicyInfoMapper.selectInsuranceByLoanId(loanId);
		if(dbInfo!=null && dbInfo.size()>0) {
			MarvelsLogUtil.getInstance().info(dbInfo.get(0).getLoanId()+"保单数据已经存在不能新增");
			return null;
		}else {
			List<BasicDataDTO> insuranceTypeList = null;//保单类型
			List<BasicDataDTO> lifeInsuranceTypeList = null;//寿险类型
			try {
				MarvelsResultDTO  resultDto = taskProcessService.getBasicDatas();
				Map<String, List<BasicDataDTO>> baseDataMap = (Map<String, List<BasicDataDTO>>) resultDto.getData();
				if(baseDataMap!=null){
					insuranceTypeList = baseDataMap.get(MarvelsConstant.INSURANCE_TYPE_LIST);
					lifeInsuranceTypeList = baseDataMap.get(MarvelsConstant.LIFE_INSURANCE_TYPE_LIST);
				}
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error("获取保单类型/寿险类型异常========》》》》》》"+e);
			}

			for (McamAcLoanApplyBdInfo BdInfo : dto) {
				if (BdInfo.getId() != null) {
					throw new MarvelsBusinessException(BdInfo.getLoanId() + "保单数据由于有id" + BdInfo.getId() + "所以无法做入库处理！");
				}
				if(org.apache.commons.lang.StringUtils.isBlank(BdInfo.getUpdatedBy())) {
					BdInfo.setUpdatedBy("SYSTEM");
				}
				if(org.apache.commons.lang.StringUtils.isBlank(BdInfo.getCreatedBy())) {
					BdInfo.setCreatedBy("SYSTEM");
				}
				//兼容老系统类型为中文，名称为空问题
				if(!CollectionUtils.isEmpty(insuranceTypeList)){
					for (BasicDataDTO basicDataDTO : insuranceTypeList) {
						if(StringUtils.isEmpty(BdInfo.getInsuranceName()) && basicDataDTO.getName().equals(BdInfo.getInsuranceType())){
							BdInfo.setInsuranceType(basicDataDTO.getCode());
							BdInfo.setInsuranceName(BdInfo.getInsuranceType());
							break;
						}
					}
				}
				if(!CollectionUtils.isEmpty(lifeInsuranceTypeList)){
					for (BasicDataDTO basicDataDTO : lifeInsuranceTypeList) {
						if(StringUtils.isEmpty(BdInfo.getLifeInsuranceTypeCode()) && basicDataDTO.getName().equals(BdInfo.getLifeInsuranceType())){
							BdInfo.setLifeInsuranceTypeCode(basicDataDTO.getCode());
							BdInfo.setLifeInsuranceType(BdInfo.getInsuranceType());
							break;
						}
					}
				}
				//保存保单信息
				Integer msg = mcamLoanApplyInfoService.saveMcamPolicyInfo(BdInfo);
				if(msg < 1){
					MarvelsLogUtil.getInstance().info("保单数据保存失败");
				}
			}
		}

		return dto;
	}

	/**
	 * 同步影像文件
	 */
	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	@Override
	public List<McamAcLoanApplyImageInfo> synchronizeAttachment(String loanId) throws MarvelsBusinessException {
		MarvelsLogUtil.getInstance().info("Synchronize_Data_Attachment_loanId:" + loanId);
		List<McamAcLoanApplyImageInfo> dto = loanApplySynchronizeApi.queryImageInfo(loanId);
		MarvelsLogUtil.getInstance().info(loanId+"synchronizeInsurancePolicy_dto:"+dto);
		if (dto == null) {
			throw new MarvelsBusinessException("影像文件同步失败loanId:" + loanId);
		}
		List<LaAttachmentDTO> dbInfo = this.attachmentInfoMapper.selectAttachmentInf(null, loanId);
		if(dbInfo!=null &&  dbInfo.size() > 0) {
			MarvelsLogUtil.getInstance().info(loanId+"映像数据已经存在不能新增");
		}else {
			for (McamAcLoanApplyImageInfo mcamAcLoanApplyImageInfo : dto) {
				if(StringUtils.isBlank(mcamAcLoanApplyImageInfo.getCreatedBy())) {
					mcamAcLoanApplyImageInfo.setCreatedBy("SYSTEM");
				}
				if(mcamAcLoanApplyImageInfo.getUploadTime()==null) {
					mcamAcLoanApplyImageInfo.setUploadTime(new Date());
				}
				mcamAcLoanApplyImageInfo.setUpdatedBy("SYSTEM");
				mcamAcLoanApplyImageInfo.setCreatedDate(mcamAcLoanApplyImageInfo.getUploadTime());
				mcamAcLoanApplyImageInfo.setUpdatedDate(mcamAcLoanApplyImageInfo.getUploadTime());
				Integer msg = mcamLoanApplyInfoService.saveMcamAttachmentInfo(mcamAcLoanApplyImageInfo);
				if(msg < 1){
					MarvelsLogUtil.getInstance().info("影像数据保存失败"+dto);
				}
			}
		}
		return dto;
	}
	/**
	 *同步联系人信息
	 */
	@Override
	public List<LoanApplyContactInfoDTO> synchronizeLinkman(String loanId) throws MarvelsBusinessException {
		McamLoanApplyInfoDTO applyInfoDto = mcamLoanApplyInfoService.findMcamLoanApplyInfo(loanId);
		if(applyInfoDto==null){
			throw new MarvelsBusinessException("联系人同步========无对应的贷款信息:" + loanId);
		}
		MarvelsLogUtil.getInstance().info("Synchronize_Data_Linkman_loanId:" + loanId);
		List<LoanApplyContactInfoDTO>  linkedManList = loanApplySynchronizeApi.queryLinkmanList(loanId);
		if (linkedManList == null) {
			throw new MarvelsBusinessException("联系人同步失败loanId:" + loanId);
		}

		List<LoanApplyContactInfoDTO> contacts =  taskProcessMapper.selectContacts(loanId);
		if(!CollectionUtils.isEmpty(contacts)){
			MarvelsLogUtil.getInstance().info(loanId+"联系人数据已经存在不能新增");
		}else{
			//默认添加一条本人信息
			LoanApplyContactInfoDTO linkManDto = new LoanApplyContactInfoDTO();
			linkManDto.setRelationCode("00");
			linkManDto.setContactName(applyInfoDto.getCustName());
			linkManDto.setRelationName("本人");
			linkManDto.setLoanId(loanId);
			linkManDto.setContactMobile(applyInfoDto.getMobileNo());
			linkManDto.setCreatedBy("SYSTEM");
			linkManDto.setUpdatedBy("SYSTEM");
			linkManDto.setIsEmergencyContact(1);
			linkManDto.setApproveStatus("Y");
			taskProcessMapper.insertContact(linkManDto);

			for (LoanApplyContactInfoDTO linkMan : linkedManList) {
				if(StringUtils.isBlank(linkMan.getCreatedBy())) {
					linkMan.setCreatedBy("SYSTEM");
				}
				if(StringUtils.isBlank(linkMan.getUpdatedBy())) {
					linkMan.setUpdatedBy("SYSTEM");
				}
				//如果relationCode为一位数，前面补0
				if(StringUtils.isNotEmpty(linkMan.getRelationCode())&&linkMan.getRelationCode().length()==1){
					linkMan.setRelationCode("0"+linkMan.getRelationCode());
				}
				linkMan.setApproveStatus("Y");
				Integer count = taskProcessMapper.insertContact(linkMan);
				if(count < 1){
					MarvelsLogUtil.getInstance().info("联系人信息保存失败"+linkMan);
				}
			}
		}
		return linkedManList;
	}
}
